package com.lovo.util.utils;

import org.bouncycastle.util.encoders.Base64Encoder;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Base64;
import java.util.UUID;

/**
 * 文件处理工具类
 */
public class FileUtils {
    //绝对路径
    //private static String absolutePath="/mnt/imgs/";
    private static String absolutePath="C:\\Users\\10745\\Desktop\\素材\\java/";

    /**
     * 上传文件到本地磁盘
     * @param file 文件对象
     * @return 返回新的文件名称
     * @throws IOException
     */
    public static String uploadFileAb(MultipartFile file) throws IOException {
        //获取文件上传时候的名称
        String fileName = file.getOriginalFilename();
        //截取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //得到新文件名
        String newFileName = UUID.randomUUID()+suffixName;
        file.transferTo(new File(absolutePath+newFileName));
        return newFileName;
    }

    /**
     * 获取base64编码图片
     * @param ImgName
     * @return
     * @throws IOException
     */
    public static String getImgFile(String ImgName) throws IOException {
        byte[] buffer = null;
        try{
            File imgFile = new File(absolutePath+ImgName);
            FileInputStream inputFile = new FileInputStream(imgFile);
            buffer = new byte[(int)imgFile.length()];
            inputFile.read(buffer);
            inputFile.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        String strImg="data:image/png;base64,"+Base64.getEncoder().encodeToString(buffer);
        //String replace = strImg.replace("=","");
        System.out.println(strImg);
        return strImg;
    }
}
